//
//  ZGSSearchViewController.m
//  Tour
//
//  Created by dllo on 15/10/30.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "ZGSSearchViewController.h"
#import "AdvanceEdit.h"
#import "ZGSSearchCell.h"
#import "ZGSHotModelTwo.h"
#import <MJRefresh.h>
#import "ScrollWebViewController.h"
#import "ZGSDestinationCityController.h"
#import "ZGSSearchGoToViewController.h"
#import "ZGSCountryViewController.h"
@interface ZGSSearchViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain)UISearchBar *searchBar;
@property (nonatomic, retain)NSString *str;
@property (nonatomic, retain)NSMutableArray *arr;
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)UIScrollView *scrollView;
//@property (nonatomic, retain)
@end

@implementation ZGSSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.arr = [NSMutableArray array];
    [self creatScreachView];
//    [self creatTableView];
    [self creatData];
    
}
- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.hidesBarsOnSwipe = NO;
}

- (void)creatScreachView{
    self.navigationController.navigationBarHidden = NO;
    
    self.view.backgroundColor =[UIColor whiteColor];
//    self.navigationItem.hidesBackButton = YES;
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 100)];
    [self.searchBar setPlaceholder:@"Search"];
    [self.searchBar setBarStyle:UIBarStyleDefault];
    [self.searchBar setTranslucent:NO];// 是否透明
    //[self.searchBar setSearchFieldBackgroundPositionAdjustment:UIOffsetMake(30, 0)];//设置搜索中文本框背景偏移量
    [self.searchBar setShowsSearchResultsButton:YES];
    //[self.searchBar setSearchTextPositionAdjustment:UIOffsetMake(30, 0)];//设置搜索中文本框文本偏移量
    [self.searchBar setKeyboardType:UIKeyboardTypeEmailAddress];//设置键盘样式
//     [self.searchBar setKeyboardType:UIKeyboardTypeEmailAddress];
    
    //设置搜索框下边的分栏条
    [self.searchBar setShowsScopeBar:NO];//是否显示分栏条
    [self.searchBar setShowsCancelButton:YES];//是否显示取消按钮
    [self.view addSubview:self.searchBar];
     self.searchBar.delegate = self;// 设置代理
//    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 100, WIDTH, HEIGHT - 164)];
    self.scrollView.contentSize = CGSizeMake(WIDTH * 3, HEIGHT - 100);
    [self.view addSubview:self.scrollView];
    
    
    
    self.tableView.separatorStyle = NO;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 100, WIDTH, HEIGHT - 100) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.rowHeight = HEIGHT / 5;
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    [self.tableView registerClass:[ZGSSearchCell class] forCellReuseIdentifier:@"reuse"];
    [self.view addSubview:self.tableView];
    [_tableView release];
//    self.tableView.footer
//    self.navigationItem.
//    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(header)];
    //上啦
//    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footer)];

    
}


- (void)creatData{
}

- (void)footer{

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZGSSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
    NSString *address = [NSString stringWithFormat:@"%@/%@", [self.arr[indexPath.row] parent_parentname], [self.arr[indexPath.row] parentname]];
    cell.labelAddress.text = address;
    [cell.viewImage sd_setImageWithURL:[NSURL URLWithString:[self.arr[indexPath.row] cover_image_1600]] placeholderImage:[UIImage imageNamed:@"10.jpeg"]];
    
    cell.labelName.text = [self.arr[indexPath.row] cnname];
    cell.labelEnglish.text = [self.arr[indexPath.row] enname];
    cell.labelLeixing.text = [self.arr[indexPath.row] label];
    NSMutableAttributedString *cnnameString = [[NSMutableAttributedString alloc]initWithString:cell.labelName.text];
    NSRange range = [cell.labelName.text rangeOfString:self.searchBar.text];
    // 给副文本添加属性
    [cnnameString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    cell.labelName.attributedText = cnnameString;
    return cell;
}

// UISearchBar得到焦点并开始编辑时，执行该方法
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
//    [self.searchBar setShowsCancelButton:YES animated:YES];
//    [self.navigationController setNavigationBarHidden:YES animated:YES];
//    [self.controlAccessoryView:0.9];// 显示遮盖层。
    return YES;
    
}

// 取消按钮被按下时，执行的方法
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self.searchBar resignFirstResponder];
//    [self.searchBar setShowsCancelButton:NO animated:YES];
//    [liveViewAreaTable searchDataBySearchString:nil];// 搜索tableView数据
//    [self.navigationController setNavigationBarHidden:NO animated:YES];
//    [self controlAccessoryView:0];// 隐藏遮盖层。
    [self.navigationController popToRootViewControllerAnimated:YES];
}

// 键盘中，搜索按钮被按下，执行的方法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
//    NSLog(@"---%@",searchBar.text);
    [self.searchBar resignFirstResponder];// 放弃第一响应者
//    [liveViewAreaTable searchDataBySearchString:searchBar.text];
//    [self.navigationController setNavigationBarHidden:NO animated:YES];
//    [self controlAccessoryView:0];// 隐藏遮盖层。
//    self.str =searchBar.text;
    self.str = [searchBar.text  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *strtmp = [NSString stringWithFormat:@"http://open.qyer.com/qyer/search/index?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&keyword=%@&lat=38.88261258247817&lon=121.539418309187&page=1&place_field=country%%7Ccity%%7Cpoi&track_app_channel=App%%2520Store&track_app_version=6.7&track_device_info=iPhone7%%2C1&track_deviceid=CD8DD9AA-C227-45CD-A07E-DA485B537E39&track_os=ios%%25208.4.1&type=place&v=1", self.str];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:strtmp parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        NSLog(@"%@", dic);
        self.arr = [ZGSHotModelTwo baseModelArr:dic[@"data"][@"entry"]];
        for (ZGSHotModelTwo *two in self.arr) {
            if ([two.label  isEqual: @"美食"]) {
                [self.arr removeObject:two];
                break;
            }
        }
        NSLog(@"%@!!!!!!!!!", self.arr);
        [self.tableView reloadData];
//        [self.tableView.footer endRefreshing];
        if (self.arr.count == 0) {
            UILabel *label = [[UILabel alloc] initWithFrame:self.tableView.frame];
            label.text = @"没有搜索结果";
            label.textAlignment = 1;
            [self.view addSubview:label];
            label.backgroundColor = [UIColor whiteColor];
            [label release];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
    }];

    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    ScrollWebViewController *webVC = [[ScrollWebViewController alloc] init];
    
#pragma mark 根据搜索出来的类型进行判断跳转的地方
    
    
    if ([[self.arr[indexPath.row] label]  isEqual: @"城市"]) {
        ZGSCountryViewController *country = [[ZGSCountryViewController alloc] init];
        country.cityid = [self.arr[indexPath.row] idd];
        country.name = [self.arr[indexPath.row] cnname];
        [self.navigationController pushViewController:country animated:YES];
        

        
    }else if([[self.arr[indexPath.row] label]  isEqual: @"国家"]){
        ZGSDestinationCityController *zgsDesVC = [[ZGSDestinationCityController alloc] init];
//        webVC.urlStr = strWeb;
        zgsDesVC.cityid = [self.arr[indexPath.row] idd];
        zgsDesVC.name = [self.arr[indexPath.row] cnname];
        [self.navigationController pushViewController:zgsDesVC animated:YES];
    }else{
        ZGSSearchGoToViewController *searchGoVC = [[ZGSSearchGoToViewController alloc] init];
        NSString *strWeb = [NSString stringWithFormat:@"http://open.qyer.com/qyer/footprint/poi_detail?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&lat=38.88265078721675&lon=121.5394685243192&page=1&poi_id=%@&screensize=1125&track_app_channel=App%%2520Store&track_app_version=6.7&track_device_info=iPhone7%%2C1&track_deviceid=CD8DD9AA-C227-45CD-A07E-DA485B537E39&track_os=ios%%25208.4.1&v=1", [self.arr[indexPath.row] idd]];
        searchGoVC.str = strWeb;
        [self.navigationController pushViewController:searchGoVC animated:YES];
//        webVC.urlStr = strWeb;
//        [self presentViewController:webVC animated:YES completion:^{
        
            
        
//        NSLog(@"%@", webVC.urlStr);
    }
    
}

// 当搜索内容变化时，执行该方法。很有用，可以实现时实搜索
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;{
   // NSLog(@"textDidChange---%@",searchBar.text);
    //[liveViewAreaTable searchDataBySearchString:searchBar.text];// 搜索tableView数据
//    [self controlAccessoryView:0];// 隐藏遮盖层。
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
